package com.cloudbroker.bcs.platform.dav.common.extservice.store;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.context.RuntimeContext;
import com.cloudbroker.bcs.common.util.ValueUtil;

public class StoreServiceFactory {
    
private static final Logger LOG = LoggerFactory.getLogger(StoreServiceFactory.class);
    
    private static StoreServiceFactory instance = new StoreServiceFactory();
    
    private StoreService service;
    
    private String implType;
    
    private StoreServiceFactory() {}
    
    public static StoreServiceFactory getInstance() {
    	return instance;
    }

	public StoreService getStoreService() {
		// 取实现类型，如果没有就按默认的
        String _implType = ConfigUtil.get(StoreFields.PROP_IMPL_TYPE , StoreFields.IMPL_TYPE_FILE);
        if (service != null && _implType.equalsIgnoreCase(implType)) {
        	return service;
        }
        try {
        	Map<String, Object> params = new HashMap<String, Object>();
        	addImplConfig(params, _implType);
            // 按实现类型获取bean
        	StoreService storeService = RuntimeContext.getBean(_implType, StoreService.class);
        	storeService.initialize(params);
        	service = storeService;
        	implType = _implType;
            return storeService;
        } catch (NoSuchBeanDefinitionException e) {
            // 实现bean不存在则报告错误
            LOG.error("no such implType: " + _implType, e);
        } catch (Exception e) {
            LOG.error("Operation failed.", e);
        }
        return null;
	}
	
	@SuppressWarnings("unchecked")
	private void addImplConfig(Map<String, Object> request, String implType) {
		Map<String, Object> implConfig = (Map<String, Object>) ConfigUtil.getProp().get(implType);
		if (null != implConfig && !implConfig.isEmpty()) {
			for (Entry<String, Object> entry : implConfig.entrySet()) {
				request.put(entry.getKey(), ValueUtil.getString(entry.getValue(), null));
			}
		}
	}

}
